package com.example.frn.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.example.frn.dao.AdminMapper;
import com.example.frn.entity.Admin;
import com.example.frn.entity.Category;
import com.example.frn.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//对当前service数据操作开启缓存
@Cacheable("adminService")
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper mapper;
    /**
     * 保存用户登录信息
     *
     * @param admin@return 成功返回true 失败返回false
     */
    @Override
    @CacheEvict(allEntries = true)
    public boolean save(Admin admin) {
        //密码明文 例如123456
        String passwd = admin.getPasswd();
        //对密码进行加密
        String secretPasswd = SecureUtil.md5(passwd);
        admin.setPasswd(secretPasswd);
        return mapper.save(admin)>0;
    }

    /**
     * 根据ID删除类别
     *
     * @param id 类别ID
     * @return 成功返回true 失败返回false
     */
    @Override
    public boolean removeById(Integer id) {
        return mapper.deleteById(id)>0;
    }

    /**
     * 根据ID更新类别
     *
     * @param admin 类别实体对象
     * @return 成功返回true 失败返回false
     */
    @Override
    @CacheEvict(allEntries = true)
    public boolean updateById(Admin admin) {
        admin.setPasswd(SecureUtil.md5(admin.getPasswd()));
        return mapper.updateById(admin)>0;
    }

    /**
     * 根据ID查询单个类别
     *
     * @param id 类别ID
     * @return 成功返回true 失败返回false
     */
    @Override
    //将当前方法返回的结果放入返回块
    @CachePut(key = "#root.methodName")
    public Admin getById(Integer id) {
        return mapper.selectById(id);
    }

    /**
     * 查询全部类别
     *
     * @return
     */
    @Override
    @CachePut(key = "#root.methodName")
    public List<Admin> list() {
        return mapper.List();
    }

    /**
     * 分页查询类别
     *
     * @param pageNum 当前页号
     * @param pageSize   每页显示条数
     * @return
     */
    @Override
    @CachePut(key = "#root.methodName + 'pn='+pageNum+'ps='+pageSize")
    public PageInfo<Admin> page(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list = mapper.List();
        return new PageInfo<>(list);
    }
}
